package com.hp.bon.sgw.service;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.gson.Gson;
import com.hp.bon.sgw.bean.CPUOverloadBean;
import com.hp.bon.sgw.bean.CongestionBean;
import com.hp.bon.sgw.bean.SGWStatPortBean;
import com.hp.bon.sgw.bean.SGWStatQueueBean;
import com.hp.bon.sgw.bean.SysPertriNetBean;
import com.hp.bon.sgw.convert.Xml2AVPConvetor;
import com.hp.bon.sgw.core.ChannelServer;
import com.hp.bon.sgw.core.InprogressMessageQueue;
import com.hp.bon.sgw.core.channel.IChannel;
import com.hp.bon.sgw.core.route.RouteInfo;
import com.hp.bon.sgw.domain.Node;
import com.hp.bon.sgw.domain.SGWChannel;
import com.hp.bon.sgw.dr.config.MdrmgrSrvCfg;
import com.hp.bon.sgw.start.SpringContext;
import com.hp.bon.sgw.threads.BlacklistMonitorThread;
import com.hp.bon.sgw.threads.StateAnalysThread;
import com.hp.bon.sgw.util.Comutils;
import com.hp.bon.sgw.util.RmiAgentUtil;

/**
 * 系统控制相关Service
 * 
 * @author wuzhih
 * 
 */
@Path("/")
public class SysCtrlService implements ConfigListener {

	/**
	 * Logger for this class
	 */
	private static final Logger logger = LoggerFactory.getLogger(SysCtrlService.class);

	/**
	 * 上一次执行checkSystemHealth的时间
	 */
	private volatile long prevRunedTime;
	/**
	 * 单位：秒
	 */
	private volatile int crowScanPeriod = 300;
	/**
	 * 拥塞因子比例
	 */
	private volatile double crowedCpuFactor = 30;

	/**
	 * 拥塞因子比例
	 */
	private volatile double crowedMemoryFactor = 30;

	/**
	 * 拥塞因子比例
	 */
	private volatile double crowedMsgQueuFactor = 30;

	/**
	 * 轻度拥塞下限
	 */
	private volatile double crowedLightMin;

	/**
	 * 严重拥塞下限
	 */
	private volatile double crowedServeMin;

	/**
	 * 拒绝服务下限
	 */
	private volatile double crowedDosMin;

	/**
	 * cpu告警阀值
	 */
	private volatile double cpuThreshold;

	/**
	 * 内存告警阀值
	 */
	private volatile double memThreshold;
	/**
	 * jvm内存告警阀值
	 */
	private volatile double jvmMemThreshold;

	/**
	 * 拥塞状态Bean
	 */
	protected CongestionBean congestionBean;

	/**
	 * CPUOverloadBean
	 */

	protected CPUOverloadBean cpuOverloadBean;
	/**
	 * Pertri Bean
	 */
	protected SysPertriNetBean pertriBean;
  protected DataStatusService dataStatusServ;
  private final Set<String> monitorConfKeys = new HashSet();
  protected ConfigService confSrv;
  private volatile boolean needStop;

  public SysCtrlService()
  {
    this.monitorConfKeys.add("agreement.congestion_period");
    this.monitorConfKeys.add("agreement.congestion_cpu_per");
    this.monitorConfKeys.add("agreement.congestion_mem_per");
    this.monitorConfKeys.add("agreement.congestion_msg_per");
    this.monitorConfKeys.add("agreement.congestion_1000_min");
    this.monitorConfKeys.add("agreement.congestion_2100_min");
    this.monitorConfKeys.add("agreement.congestion_9999_min");
    this.monitorConfKeys.add("system.cpu_used");
    this.monitorConfKeys.add("system.mem_used");
    this.monitorConfKeys.add("system.jvm_mem_used");

    this.monitorConfKeys.add("AGREEMENT.Period_RequestCap");
    this.monitorConfKeys.add("AGREEMENT.OutCount_RequestNoExistCap");
  }

  public boolean needStop()
  {
    return this.needStop;
  }

  public void init() {
    loadResourceConf();
    loadCongestionConf();
  }

  public void shutdown() {
    logger.info("shutdown sysctrl service ");
    logger.info(this.confSrv.saveConfigToLocal());
  }

  public void onConfigUpdated(String updatedKey)
  {
    if (updatedKey.startsWith("agreement.congestion_"))
      loadCongestionConf();
    else if (updatedKey.startsWith("system."))
      loadResourceConf();
    else
      logger.warn("not recoginized param " + updatedKey);
  }

  private void loadResourceConf()
  {
    this.cpuThreshold = this.confSrv.getDoubleValue("system.cpu_used", 80.0D);
    this.memThreshold = this.confSrv.getDoubleValue("system.mem_used", 80.0D);
    this.jvmMemThreshold = this.confSrv.getDoubleValue("system.jvm_mem_used", 80.0D);
    logger.info("set cpu alert threshold " + this.cpuThreshold + ", memory alert threshold " + this.memThreshold + ", jvm memory alert threshold " + this.jvmMemThreshold);
  }

  private void loadCongestionConf()
  {
    this.crowScanPeriod = this.confSrv.getIntValue("agreement.congestion_period", 300);
    this.crowedCpuFactor = this.confSrv.getDoubleValue("agreement.congestion_cpu_per", 33.0D);
    this.crowedMemoryFactor = this.confSrv.getDoubleValue("agreement.congestion_mem_per", 33.0D);
    this.crowedMsgQueuFactor = this.confSrv.getDoubleValue("agreement.congestion_msg_per", 33.0D);
    this.crowedLightMin = this.confSrv.getDoubleValue("agreement.congestion_1000_min", 2000.0D);
    this.crowedServeMin = this.confSrv.getDoubleValue("agreement.congestion_2100_min", 7500.0D);
    this.crowedDosMin = this.confSrv.getDoubleValue("agreement.congestion_9999_min", 9999.0D);
    StringBuilder sb = new StringBuilder().append("load conf \r\n");
    sb.append("agreement.congestion_period value:").append(this.crowScanPeriod).append("\r\n").append("agreement.congestion_cpu_per value:").append(this.crowedCpuFactor).append("\r\n").append("agreement.congestion_mem_per value:")
      .append(this.crowedMemoryFactor).append("\r\n").append("agreement.congestion_msg_per value:").append(this.crowedMsgQueuFactor).append("\r\n").append("agreement.congestion_1000_min value:").append(this.crowedLightMin).append("\r\n")
      .append("agreement.congestion_2100_min value:").append(this.crowedServeMin).append("\r\n").append("agreement.congestion_9999_min value:").append(this.crowedDosMin).append("\r\n");
    logger.info(sb.toString());
  }

  private double getJvmMemUsed() {
    long usedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
    double usedMemPer = 100.0D * (usedMem + 0.0D) / Runtime.getRuntime().maxMemory();
    return usedMemPer;
  }

  public void doPeriodJob() {
    try {
      checkSystemHealth();
    } catch (Exception e) {
      logger.warn("checkSystemHealth err:" + e);
    }
    try
    {
      checkPetriStatusChangeProgress();
    } catch (Exception e) {
      logger.warn("checkPetryStatusChangeProgress err:" + e);
    }
    try
    {
      FluxControlService.getInstance().doPeriodWork();
    } catch (Exception e) {
      logger.warn("FluxControlService.getInstance().doPeriodWork() err:" + e);
    }
    try
    {
      this.confSrv.checkLazyEffectedSysParams();
    } catch (Exception e) {
      logger.warn("checkLazyEffectedSysParams() err:" + e);
    }
    try {
		// 检查流控累计统计量 add by wanghan
		FluxControlSgwViewService.getInstance().doPeriodWork();
	} catch (Exception e) {
		logger.warn("FluxControlSgwViewService.getInstance().doPeriodWork() err:" + e);
	}
	
	try {
		// 黑名单累计统计量 add by wanghan
		BlackListSgwViewService.getInstance().doPeriodWork();
	} catch (Exception e) {
		logger.warn("BlackListSgwViewService.getInstance().doPeriodWork() err:" + e);
	}
  }

  private void checkPetriStatusChangeProgress() {
    int status = this.pertriBean.getStatus();
    if ((status == -4) || (status == -6)) {
      int pendingTotals = this.congestionBean.getInMsgQueue().getQueueSize();
      if (pendingTotals == 0) {
        int newStatus = status == -4 ? -3 : -1;
        logger.info("no more businness process in queue ,change petri status to " + SysPertriNetBean.getPertiStatusName(newStatus));
        this.pertriBean.setNewStatus(newStatus);
        shutDown();
      } else {
        logger.info("still some pending request to handle " + pendingTotals);
      }
    }
  }

  private void checkSystemHealth()
  {
    long curTime = System.currentTimeMillis();
    if (this.prevRunedTime + this.crowScanPeriod * 1000 < curTime) {
      if (logger.isDebugEnabled()) {
        logger.debug("check system health ");
      }
      this.prevRunedTime = System.currentTimeMillis();
    } else {
      return;
    }
    double[] cpuAndMemoryUsage = RmiAgentUtil.getCpuMem();
    double cpu = cpuAndMemoryUsage[0];

    this.cpuOverloadBean.swap();
    this.cpuOverloadBean.setCurCPU(cpu);

    boolean overLoad = false;
    if (cpu > this.cpuThreshold) {
      overLoad = true;
      logger.warn("cpu usage is too high ,cur is " + cpu + " ,threshold is " + this.cpuThreshold);
    }
    double memory = cpuAndMemoryUsage[1];
    if (memory > this.memThreshold) {
      overLoad = true;
      logger.warn("memory usage is too high ,cur is " + memory + " ,threshold is " + this.memThreshold);
    }
    double jvmMemUsed = getJvmMemUsed();
    if (jvmMemUsed > this.jvmMemThreshold) {
      overLoad = true;
      logger.warn("jvm memory usage is too high ,cur is " + jvmMemUsed + " ,threshold is " + this.jvmMemThreshold);
    }

    checkCrawedLevel(cpuAndMemoryUsage[0], jvmMemUsed);
  }

  private void checkCrawedLevel(double cpuUsage, double jvmMemUsed) {
    double crawedIndex = cpuUsage * this.crowedCpuFactor + jvmMemUsed * this.crowedMemoryFactor + InprogressMessageQueue.getInstance().getQueueUsage() * this.crowedMsgQueuFactor;

    int newCrawedLevel = 0;
    if (crawedIndex < this.crowedLightMin)
      newCrawedLevel = 0;
    else if (crawedIndex < this.crowedServeMin)
      newCrawedLevel = 1000;
    else if (crawedIndex >= this.crowedServeMin)
      newCrawedLevel = 2100;
    else {
      logger.warn("congestion value is illegal:" + crawedIndex);
    }
    int curLevel = this.congestionBean.getCurCrawedLevel();
    if (curLevel != newCrawedLevel) {
      this.congestionBean.swap();
      this.congestionBean.setCurCrawedLevel(newCrawedLevel);
      this.congestionBean.setCurCrawedTime(System.currentTimeMillis());
    }
    this.congestionBean.setCurCrawedIndex(crawedIndex);
    if (curLevel != newCrawedLevel) {
      logger.warn("congestion param|cpu:" + cpuUsage + "|jvmmem:" + jvmMemUsed + "|queue:" + InprogressMessageQueue.getInstance().getQueueUsage() + "|value:" + crawedIndex);
      logger.warn("congestionchanged|17003|" + curLevel + "|" + newCrawedLevel + "|" + "system congestion level changed from " + curLevel + " to " + newCrawedLevel);

      BONNetCtrlService.getInstance().notifySystemCrowdedLevel(newCrawedLevel);
      try
      {
        int bnmsCongLevel = -1;
        if (newCrawedLevel == 0) bnmsCongLevel = 0;
        else if (newCrawedLevel == 1000) bnmsCongLevel = 1;
        else if (newCrawedLevel == 2100) bnmsCongLevel = 2;

					String queueUsage = "" + InprogressMessageQueue.getInstance().getQueueUsage();
					String queueSize = "" + InprogressMessageQueue.getInstance().getQueueSize();
					String maxInprogCount = "" + InprogressMessageQueue.getInstance().getMaxInprogressCount();

        logger.warn("Send alarm congestion ctrl notify to OMC.[bnmsCongLevel=" + bnmsCongLevel + " queueUsage=" + queueUsage + " queueSize=" + queueSize + " maxInprogCount=" + maxInprogCount + " cpuUsage=" + cpuUsage + " jvmMemUsed=" + jvmMemUsed + "]");
        OmcRestService.getInstance().getOMCAlarmInterface()
          .alarmCongestionCtrlNotiry(this.confSrv.getValue("SGW_HOST_ID", null), 
          this.confSrv.getValue("SGW_HOST_ID", null), 
          ""+bnmsCongLevel, queueUsage, queueSize, maxInprogCount, ""+cpuUsage, ""+jvmMemUsed, ""+System.currentTimeMillis());
      }
      catch (Exception e)
      {
        logger.warn("Send alarm congestion ctrl notify to OMC failed:" + e.getMessage(), e);
      }
    }
  }

  public List<SGWStatPortBean> getServerPorts()
  {
    LinkedList portBeans = new LinkedList();
    for (SGWChannel node : this.confSrv.getSgwChannelMap().values()) {
      SGWStatPortBean bean = new SGWStatPortBean();
      bean.setPort(node.getUri());
      bean.setStatus("normal");
      portBeans.add(bean);
    }
    return portBeans;
  }

  public String getStatQueue(String module) {
    List quequeBeans = new LinkedList();
    SGWStatQueueBean queBean = this.congestionBean.getInMsgQueue().getQueueStatusBean();

    queBean.setName("SGW");
    quequeBeans.add(queBean);
    return new Gson().toJson(quequeBeans);
  }

  public String getSystemStatusThrupt(String module) {
    List beansLst = new LinkedList();
    int[] pendings = this.congestionBean.getInMsgQueue().getPendingCounts();
    SpringContext.getInstance().getDataStatusService().dccThruptBean.setPendingMsg(pendings[0]);
    beansLst.add(SpringContext.getInstance().getDataStatusService().dccThruptBean);
    return new Gson().toJson(beansLst);
  }
  @GET
  @Path("system/shutdown")
  @Produces({"text/plain"})
  public String shutDown() { logger.info("received shutdown request ,notify shutdown ");
    this.needStop = true;
    return "System will shutdown now!"; } 
  @GET
  @Path("sysctrl/alive")
  @Produces({"text/plain"})
  public int checkNodeAlive() {
    return this.pertriBean.getStatus();
  }
  @GET
  @Path("sgwparam/set/{paramValue:.*}/{node}")
  @Produces({"application/json"})
  public String doParamValueSet(@PathParam("paramValue") String paramValue, @PathParam("node") String node) { return this.confSrv.setSysParam(paramValue); } 
  @GET
  @Path("sgwparam/refresh")
  @Produces({"application/json"})
  public String doParamRefresh() {
    return this.confSrv.reloadSysParamFile();
  }
  @GET
  @Path("drparam/refresh")
  @Produces({"application/json"})
  public String doDrParam() { if (MdrmgrSrvCfg.getInstance().RefreshCfg(true)) {
      return "SUCCESS";
    }
    return "FAIL"; } 
  @GET
  @Path("sgwparam/list/{param:.*}/{node}")
  @Produces({"application/json"})
  public String doParamList(@PathParam("param") String param, @PathParam("node") String node) {
    return this.confSrv.listSysParams(param);
  }
  @GET
  @Path("config/reloadall/{node:.*}")
  @Produces({"text/plain;charset=utf-8"})
  public String reloadConfig() { return this.confSrv.reloadAllConfig(); } 
  @GET
  @Path("config/reloaddelaycapfile")
  @Produces({"text/plain"})
  public String loadDelayCallFile() {
    return this.confSrv.reloadDelayCallFile();
  }
  @GET
  @Path("config/reloadDictionary")
  @Produces({"text/plain"})
  public String loadDictionaryXml() { return Xml2AVPConvetor.getInstance().loadDictionaryXml(); } 
  @GET
  @Path("config/reloadrequestvalidatexml")
  @Produces({"text/plain"})
  public String loadValidatorXmls() {
    return this.confSrv.loadValidatorXmls();
  }
  @GET
  @Path("config/reloadanswervalidatexml")
  @Produces({"text/plain"})
  public String loadAckValidatorXmls() { return this.confSrv.loadAnswerXmlPatterns(); } 
  @GET
  @Path("sgwstat/runtime/{node}")
  @Produces({"application/json"})
  public String doSGWRuntime(@PathParam("node") String node) {
    return this.pertriBean.toPrint();
  }
  @GET
  @Path("system/real/queuesize")
  @Produces({"text/plain"})
  public String getQueueSize() { return new Gson().toJson(Integer.valueOf(this.congestionBean.getInMsgQueue().getQueueSize())); } 
  @GET
  @Path("system/real/queuemaxsize")
  @Produces({"text/plain"})
  public String getQueueMaxSize() {
    return new Gson().toJson(Integer.valueOf(this.congestionBean.getInMsgQueue().getMaxInprogressCount()));
  }
  @GET
  @Path("system/real/queuecontext")
  @Produces({"text/plain"})
  public String getQueneContext() { return this.congestionBean.getInMsgQueue().getQueneContext(); } 
  @GET
  @Path("system/real/blokednes")
  @Produces({"text/plain"})
  public String getBlockedNEs() {
    return new Gson().toJson(FluxControlService.getInstance().getDenniedNEMap());
  }
  @GET
  @Path("system/petristatus")
  @Produces({"text/plain"})
  public String getPetriStatus() { return this.pertriBean.getPertiStatusName(); }


  @GET
  @Path("system/petri/{status}")
  @Produces({"text/plain"})
  public String doSysPetriChange(@PathParam("status") int newStatus)
  {
    logger.info("doSysPetriChange： " + newStatus + "(" + SysPertriNetBean.getPertiStatusName(newStatus) + ")");
    if (!this.pertriBean.switchStatus(newStatus)) {
      String msg = "FAIL: can't switch from " + this.pertriBean.getPertiStatusName() + " to " + SysPertriNetBean.getPertiStatusName(newStatus);
      logger.info(msg);
      return msg;
    }
    if (newStatus == 0)
    {
      return BONNetCtrlService.getInstance().sendActive();
    }if (newStatus == -2)
    {
      return BONNetCtrlService.getInstance().sendDeActive();
    }if (newStatus == -3) {
      logger.info("prepare to maintaince ");

      BONNetCtrlService.getInstance().sendDeActive();
      logger.info("change system status to prepare maintaince ");
      this.pertriBean.setNewStatus(-4);
    } else if (newStatus == -1) {
      logger.info("perpare to offline ");

      BONNetCtrlService.getInstance().sendDeActive();
      logger.info("change system status to prepare offline ");
      this.pertriBean.setNewStatus(-6);
    } else {
      return "FAIL: not supported status change " + SysPertriNetBean.getPertiStatusName(newStatus);
    }
    return "SUCCESS: please standby for system change status ssss";
  }

  @GET
  @Path("sgwcheckpoint/doCheckpoint/{node}")
  @Produces({"application/json"})
  public String doCheckpoint(@PathParam("node") String node)
  {
    return this.confSrv.saveConfigToLocal();
  }
  @GET
  @Path("system/real/threads")
  @Produces({"text/plain"})
  public int getJavaThreadsCount() { ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    return threadBean.getAllThreadIds().length; }

  @GET
  @Path("system/real/threadinfo")
  @Produces({"application/json"})
  public String getJavaThreadsInfo()
  {
    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    List list = new ArrayList();
    long[] threadIDs = threadBean.getAllThreadIds();
    for (long threadID : threadIDs) {
      ThreadInfo infs = threadBean.getThreadInfo(threadID, 1);
      list.add(infs);
    }

    return new Gson().toJson(list);
  }
  @GET
  @Path("system/resource/jvmmemkb")
  @Produces({"text/plain"})
  public String getJvmMemKB() {
    return new Gson().toJson(new long[] { Runtime.getRuntime().freeMemory() / 1024L, Runtime.getRuntime().totalMemory() / 1024L, Runtime.getRuntime().maxMemory() / 1024L });
  }
  @GET
  @Path("system/resource/jvmmemuesd")
  @Produces({"text/plain"})
  public String getJvmMemUsedPer() {
    return new Gson().toJson(Double.valueOf(getJvmMemUsed()));
  }
  @GET
  @Path("system/resource/fullgc")
  @Produces({"text/plain"})
  public String doFullGC() { System.gc();
    return "SUCCESS"; } 
  @GET
  @Path("system/resource/monitor")
  @Produces({"text/plain"})
  public String monitor() {
    StringBuilder sb = new StringBuilder();
    double[] cpumem = RmiAgentUtil.getCpuMem();
    sb.append(Comutils.formatTime(System.currentTimeMillis(), "yyyyMMdd HH:mm:ss.SSS") + "|" + cpumem[0] + "|" + cpumem[1] + "|" + InprogressMessageQueue.getInstance().getQueueSize() + "|" + getJvmMemUsedPer() + "|" + getJavaThreadsCount());
    return sb.toString();
  }
  @GET
  @Path("system/nodestatus")
  @Produces({"text/plain"})
  public String getRealNodeStatus() { 
	ConcurrentHashMap<String, Node> map = ConfigService.name2NodeMap;
    Map<Integer, SGWChannel> map2 = ConfigService.sgwChannelMap;
    StringBuilder sb = new StringBuilder();
    sb.append("Channel status:\r\n");
    for (Entry entry : map2.entrySet()) {
      sb.append(((SGWChannel)entry.getValue()).getChannelHost() + "=[" + (((SGWChannel)entry.getValue()).getStatus() == 1 ? "ON_LINE" : "OFF_LINE") + "," + Comutils.formatTime(((SGWChannel)entry.getValue()).getStatusTime(), "yyyy-MM-dd HH:mm:ss.SSS") + "]");
      sb.append("\r\n");
    }
    sb.append("\r\nNode status:\r\n");
    for (Entry entry : map.entrySet()) {
      sb.append((String)entry.getKey() + "=[" + (((Node)entry.getValue()).getStatus() == 1 ? "ON_LINE" : "OFF_LINE") + "," + Comutils.formatTime(((Node)entry.getValue()).getStatusTime(), "yyyy-MM-dd HH:mm:ss.SSS") + "]");
      sb.append("\r\n");
    }
    return sb.toString(); } 
  @GET
  @Path("route/find/{capa}")
  @Produces({"text/plain;charset=utf-8"})
  public String findRoute(@PathParam("capa") String capa) {
    RouteInfo route = ChannelServer.findRoute(capa.trim());
    if (route != null) {
      return "[next:" + route.curNode.getHostId() + ", status:" + route.result + "]";
    }
    return "cannot find route";
  }
  @GET
  @Path("business/blacklist")
  @Produces({"text/plain"})
  public String getBlackList() { StringBuilder sb = new StringBuilder();
    ConcurrentHashMap<String, Date> map = BlacklistMonitorThread.getInstance().getBlackList();
    for (Entry entry : map.entrySet()) {
      sb.append((String)entry.getKey() + ", expire time:" + Comutils.formatTime((Date)entry.getValue(), "yyyy-MM-dd HH:mm:ss") + "\r\n");
    }
    return sb.toString(); } 
  @GET
  @Path("active/{nodeId}")
  @Produces({"text/plain"})
  public String sendActiveNode(@PathParam("nodeId") String nodeId) {
    try {
      return BONNetCtrlService.getInstance().sendNodeActiveOrDeActive(Integer.valueOf(nodeId), true);
    } catch (Exception e) {
      return e.toString();
    }
  }

  @GET
  @Path("deactive/{nodeId}")
  @Produces({"text/plain"})
  public String sendDeActiveNode(@PathParam("nodeId") String nodeId) {
    try { return BONNetCtrlService.getInstance().sendNodeActiveOrDeActive(Integer.valueOf(nodeId), false);
    } catch (Exception e) {
      return e.toString();
    }
  }
  @GET
  @Path("channel/state")
  @Produces({"text/plain"})
  public String channelState() { StringBuilder sb = new StringBuilder();
    for (IChannel channel : ChannelServer.channelMap.values()) {
      SGWChannel sgwChannel = channel.getSGWChannel();
      if (sgwChannel.getStatus() == 1)
      {
        sb.append(sgwChannel.getChannelType()).append("-").append(sgwChannel.getChannelHost());
        sb.append(":QueueSize=").append(channel.getThreadPoolQueueSize());
        sb.append(",ThreadPoolSize=").append(channel.getThreadPoolSize());
        sb.append(",ActiveThread=").append(channel.getThreadPoolActiveCount());
        sb.append("\r\n");
      }
    }
    return sb.toString(); } 
  @GET
  @Path("msg/rate")
  @Produces({"text/plain"})
  public String msgRate() { return StateAnalysThread.getInstance().getMsgRateInfo(); }


  @Autowired
  public void setConfSrv(ConfigService confSrv)
  {
    this.confSrv = confSrv;
    confSrv.addConfigListener(this);
  }

  public Set<String> monitorConfKeys()
  {
    return this.monitorConfKeys;
  }

  @Autowired
  public void setCongestionBean(CongestionBean congestionBean) {
    this.congestionBean = congestionBean;
  }

  @Autowired
  public void setPertriBean(SysPertriNetBean pertriBean) {
    this.pertriBean = pertriBean;
  }

  @Autowired
  public void setCpuOverloadBean(CPUOverloadBean cpuOverloadBean) {
    this.cpuOverloadBean = cpuOverloadBean;
  }

  @Autowired
  public void setDataStatusServ(DataStatusService dataStatusServ) {
    this.dataStatusServ = dataStatusServ;
  }
}